import { observer } from 'mobx-react'
import { useStore } from '@renderer/store'
import { useEffect, useState } from 'react'

import { IconHome, IconMenu, IconSave, IconShareAlt } from '@arco-design/web-react/icon'
import { Link, useNavigate } from 'react-router-dom'
import { Button, Input, Message } from '@arco-design/web-react'
import EditorJS from '@editorjs/editorjs'
import Header from '@editorjs/header'
import Paragraph from '@editorjs/paragraph'
import LinkTool from '@editorjs/link'
import List from '@editorjs/list'
import Checklist from '@editorjs/checklist'
import Table from '@editorjs/table'
import RawTool from '@editorjs/raw'
import ImageTool from '@editorjs/image'
import Quote from '@editorjs/quote'
import Embed from '@editorjs/embed'
import Code from '@editorjs/code'
import Delimiter from '@editorjs/delimiter'
import AlignmentTuneTool from '@renderer/components/alignment/index'
import Underline from '@editorjs/underline' // 下划线
import Strikethrough from '@sotaproject/strikethrough' // 剧中划线
import ColorPlugin from 'editorjs-text-color-plugin'

import { useLocation } from 'react-router-dom'
import qs from 'query-string'
import html2canvas from 'html2canvas'

export function useQuery() {
  const { search } = useLocation()
  return (qs.parse(search))
}


function Note() {
  const { noteStore } = useStore()
  const navigate = useNavigate()
  const query = useQuery()
  const { id } = query

  const [noteDetail, setNoteDetail] = useState({})
  const [editor, setEditor] = useState(null)
  const [title, setTitle] = useState(undefined)

  useEffect(() => {
    let note = {}
    if (id) {
      note = noteStore.getNote(id)
      console.log('query', id, note)

      setTitle(note.title)
      setNoteDetail(note)
    }

    // 使用浏览器的 API 更新页面标题
    const editorjs = new EditorJS({
      /**
       * Id of Element that should contain the Editor
       */
      holder: 'editorjs',

      /**
       * Available Tools list.
       * Pass Tool's class or Settings object for each Tool you want to use
       */
      tools: {
        underline: Underline,
        strikethrough: Strikethrough,
        Color: {
          class: ColorPlugin, // if load from CDN, please try: window.ColorPlugin
          config: {
            colorCollections: ['#EC7878','#9C27B0','#673AB7','#3F51B5','#0070FF','#03A9F4','#00BCD4','#4CAF50','#8BC34A','#CDDC39', '#FFF'],
            defaultColor: '#FF1300',
            type: 'text',
            customPicker: true // add a button to allow selecting any colour
          }
        },
        Marker: {
          class: ColorPlugin, // if load from CDN, please try: window.ColorPlugin
          config: {
            defaultColor: '#FFBF00',
            type: 'marker',
            icon: `<svg fill="#000000" height="200px" width="200px" version="1.1" id="Icons" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 32 32" xml:space="preserve"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <path d="M17.6,6L6.9,16.7c-0.2,0.2-0.3,0.4-0.3,0.6L6,23.9c0,0.3,0.1,0.6,0.3,0.8C6.5,24.9,6.7,25,7,25c0,0,0.1,0,0.1,0l6.6-0.6 c0.2,0,0.5-0.1,0.6-0.3L25,13.4L17.6,6z"></path> <path d="M26.4,12l1.4-1.4c1.2-1.2,1.1-3.1-0.1-4.3l-3-3c-0.6-0.6-1.3-0.9-2.2-0.9c-0.8,0-1.6,0.3-2.2,0.9L19,4.6L26.4,12z"></path> </g> <g> <path d="M28,29H4c-0.6,0-1-0.4-1-1s0.4-1,1-1h24c0.6,0,1,0.4,1,1S28.6,29,28,29z"></path> </g> </g></svg>`
          }
        },
        header: {
          class: Header,
          tunes: ['anyTuneName'],
        },
        paragraph: {
          class: Paragraph,
          inlineToolbar: true,
          tunes: ['anyTuneName'],
        },
        anyTuneName: {
          class: AlignmentTuneTool,
          config: {
            default: 'left',
            blocks: {
              header: 'center',
              list: 'left'
            }
          },
        },
        linkTool: {
          class: LinkTool,
          inlineToolbar: true
        },
        list: {
          class: List,
          inlineToolbar: true
        },
        checklist: {
          class: Checklist,
          inlineToolbar: true
        },
        raw: {
          class: RawTool,
          inlineToolbar: true
        },
        table: {
          class: Table,
          inlineToolbar: true
        },
        // image: SimpleImage,
        image: {
          class: ImageTool,
          inlineToolbar: true
        },
        quote: {
          class: Quote,
          inlineToolbar: true
        },
        embed: {
          class: Embed,
          inlineToolbar: true
        },
        code: {
          class: Code,
          inlineToolbar: true
        },
        delimiter: {
          class: Delimiter,
          inlineToolbar: true
        },
      },
      /**
       * Enable autofocus
       */
      autofocus: true,
      onReady: () => {
        console.log('Editor.js is ready to work!')
      },
      data: note.detail ? note.detail : {}
    })
    console.log('editor', editorjs)
    setEditor(editorjs)
  }, [id])

  const handleGoNote = (key) => {
    navigate('/home', { replace: true })
  }

  const handleSave = async () => {
    if (!title) {
      Message.warning('请输入笔记标题!')
      return false
    }
    try {
      const picDom = document.getElementById('editorjs')
      const imageBase64 = await convertToImage(picDom)
      editor
        .save()
        .then((outputData) => {
          console.log('Article data: ', window.api, outputData)
          if (noteDetail.id) {
            noteStore.saveNote({
              ...noteDetail,
              title,
              detail: outputData,
              image: imageBase64
            }).then(res => {
              handleGoNote()
            })
          } else {
            noteStore.saveNote({
              title,
              detail: outputData,
              image: imageBase64,
              isBookmark: 0,
              isDelete: 0
            }).then(res => {
              handleGoNote()
            })
          }
        })
        .catch((error) => {
          Message.error(error)
          console.log('Saving failed: ', error)
        })
    } catch (e) {
      Message.warning(e)
    }
  }

  const handleImage = () => {
    try {
      const picDom = document.getElementById('editorjs')
      convertToImage(picDom).then(res => {
        console.log('笔记预览', res)
        // 将图片下载到本地
        var x = new XMLHttpRequest()
        x.open('GET', res, true)
        x.responseType = 'blob'
        x.onload = function(e) {
          var url = window.URL.createObjectURL(x.response)
          var a = document.createElement('a')
          a.href = url
          a.download = '笔记预览'
          a.click()
        }
        x.send()
      })
    } catch (e) {

    }
  }

  // 功能：生成快照
  const convertToImage = (container, options = {}) => {
    // 1. 设置放大倍数
    const scale = window.devicePixelRatio
    // 2. 传入节点原始宽高
    const _width = container.offsetWidth
    const _height = container.offsetHeight
    // 3. html2canvas配置项
    const ops = {
      _width,
      _height,
      useCORS: true,
      allowTaint: false,
      background: "#ffffff", // 一定要添加背景颜色，否则出来的图片，背景全部都是透明的
      scale: scale, // 处理模糊问题
      dpi: 300, // 处理模糊问题
    }
    return html2canvas(container, ops).then(canvas => {
      // 4. 返回图片的二进制数据
      return canvas.toDataURL('image/png')
    })
  }

  return <>
    <div className="page-edit">
      <div className="header">
        <div className="home">
          <Link to={'/home'}><Button icon={<IconHome />}></Button></Link>
        </div>
        <div className="ml-12 mr-12">
          <Button icon={<IconMenu />}></Button>
        </div>
        <Input value={title} onChange={(val) => setTitle(val)} allowClear placeholder="Notes title" />
        <div className="ml-12 mr-12">
          <Button type="primary" icon={<IconSave />} onClick={handleSave}></Button>
        </div>
        <div className="share">
          <Button icon={<IconShareAlt />} onClick={handleImage}></Button>
        </div>
      </div>
      <div className="editor-wrapper">
        <div className="editor" id="editorjs">
        </div>
      </div>
    </div>
  </>
}

export default observer(Note)
